package com.example.baselibrary.net.process;

import androidx.annotation.Nullable;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * 为了获取网络请求进度的拦截器，用于包装请求报文和响应报文
 */
public class ProcessInterceptor implements Interceptor {
    //请求进度监听器，不能为空
    private ProcessListener mRequestProcessListener;
    //响应进度监听器
    private ProcessListener mResponseProcessLstener;

    public static final int JUST_REQUEST = 0;
    public static final int JUST_RESPONSE = 0;
    public static final int BOTH_WAY = 2;

    private int mCurrentWay;

    private static final long DEFAULT_REFRESH_TIME = 150;
    //刷新时间，即两次进度刷新的间隔时间
    private long mRefreshTime = DEFAULT_REFRESH_TIME;


    public ProcessInterceptor(@Nullable ProcessListener listener, int type) {
        if (type == JUST_REQUEST) {
            mRequestProcessListener = listener;
            mCurrentWay = JUST_REQUEST;
        } else if (type == JUST_RESPONSE) {
            mResponseProcessLstener = listener;
            mCurrentWay = JUST_RESPONSE;
        } else {
            throw new IllegalArgumentException("if you just choose way, please choose the right type");
        }
    }

    public ProcessInterceptor(ProcessListener requestListener,
                              ProcessListener responseListener) {
        this.mRequestProcessListener = requestListener;
        this.mResponseProcessLstener = responseListener;
        mCurrentWay = BOTH_WAY;
    }

    public void setRefreshTime(long time) {
        mRefreshTime = time;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        if (mCurrentWay == BOTH_WAY) {
            return wrapResponseBody(chain.proceed(wrapRequestBody(chain.request())));
        } else if (mCurrentWay == JUST_REQUEST) {
            return chain.proceed(wrapRequestBody(chain.request()));
        } else {
            return wrapResponseBody(chain.proceed(chain.request()));
        }
    }

    /**
     * 包装请求体
     * @param request
     * @return
     */
    private Request wrapRequestBody(Request request) {
        if (request == null) {
            return null;
        }
        return request.newBuilder()
                .method(request.method(), new ProcessRequestBody(mRequestProcessListener, request.body()
                        , mRefreshTime))
                .build();
    }

    /**
     * 包装响应体
     * @param response
     * @return
     */
    private Response wrapResponseBody(Response response) {
        if (response == null) {
            return null;
        }
        return response.newBuilder()
                .body(new ProcessResponseBody(mResponseProcessLstener, response.body(),
                        mRefreshTime))
                .build();
    }
}
